// 
//  Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as
//  published by the Free Software Foundation, either version 3 of the
//  License, or (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
// 
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// 


using System;
using System.Runtime.Serialization;

namespace Galaxium.Protocol.Xmpp.Library.Utility
{
	/// <summary>
	/// Generic WeakReference with possibility to disallow garbage collection.
	///  (actually just an internal strong reference)
	/// </summary>
	[Serializable]
	public class WeakReference<T>: WeakReference
		where T: class
	{
		private bool m_locked;
		private T m_strong_ref;

		public bool IsLocked {
			get { return m_locked && IsAlive; }
			set {
				if (!IsAlive)
					throw new Exception ();
				m_locked = value;
				m_strong_ref = m_locked ? Target : null;
			}
		}
		
		public new T Target {
			get { return m_strong_ref ?? (T) base.Target; }
			set {
				base.Target = value;
				if (m_locked)
					m_strong_ref = value;
			}
		}
		
		public WeakReference (T target)
			:base (target)
		{
		}
		
		public WeakReference (T target, bool track_resurrection)
			:base (target, track_resurrection)
		{
		}

		public WeakReference (SerializationInfo info, StreamingContext context)
			:base (info, context)
		{
		}
	}
}
